package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"note-master/cache"
	"note-master/models"
	"time"
)

func AddArticle(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"message": "参数不能为空",
			"code":    500,
		})
		return
	}
	data := models.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "添加失败",
			"code":    500,
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "添加成功",
		"code":    200,
		"data":    data,
	})
	return

}

func DelArticle(c *gin.Context) {
	id := c.PostForm("id")
	err := models.DB.Delete(&models.Article{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "删除失败",
			"code":    500,
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "删除成功",
		"code":    200,
	})
	return
}

func GetArticleList(c *gin.Context) {
	var articles []models.Article
	redis_list_key := "article_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Find(&articles)
		jsonData, _ := json.Marshal(articles)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &articles)
	}
	c.JSON(200, gin.H{
		"message": "列表展示成功",
		"code":    200,
		"list":    articles,
	})
	return
}
